from django.shortcuts import render
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from decimal import Decimal

from .models import SKU
from .serializers import OrderSettlementSerializer,CommitOrderSerializer

class OrderSettlementView(APIView):
    """去结算"""
    # 指定权限
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 创建redis连接对象
        redis_conn = get_redis_connection('cart')
        # 获取请求用户
        user = request.user
        # 获取hash数据 {b'1': b'2', b'16': 1}
        cart_dict_redis = redis_conn.hgetall('cart_%s' % user.id)
        ## 获取set集合中勾选商品的sku_id {b'16}
        selected_ids = redis_conn.smembers('selected_%s' % user.id)
        # 把数据进行提取(从hash中只拿到勾选商品的sku_id和count)
        # 存储勾选商品的sku_id: count
        cart_dict = {}
        # 把勾选商品及count包装到一个新字典中以备后用 {16: 1}
        for sku_id_bytes in selected_ids:
            #遍历出来的是每个勾选的商品sku_id，再进行商品sku_id取出count值再转int（int(cart_dict_redis[sku_id_bytes])），
            # 再把count值加在键为sku_id的字典中。
            cart_dict[int(sku_id_bytes)] = int(cart_dict_redis[sku_id_bytes])
            # print(type(sku_id_bytes))


        # 获取cart_dict中的所有key
        sku_ids = cart_dict.keys()
        # 把勾选商品的sku模型查询出来
        skus = SKU.objects.filter(id__in=sku_ids)
        # 并且给每sku模型多定义一个count属性
        for sku in skus:
            sku.count = cart_dict[sku.id]
        # 创建订单序列化器进行序列化 {'freight': '10.00', 'skus': skus}
        freight = Decimal('10.00')
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})

        #响应
        return Response(serializer.data)


class CommitOrderView(CreateAPIView):
    """保存订单视图"""
    # 指定权限
    permission_classes = [IsAuthenticated]

    #指定序列化器
    serializer_class = CommitOrderSerializer